package com.helmlabs.grouper.forms.view;

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.collections.BeanMap;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;

import com.helmlabs.grouper.forms.model.Form;
import com.helmlabs.grouper.forms.model.field.AbstractField;

import freemarker.template.Configuration;
import freemarker.template.Template;

public class FreemarkerView {
	
	public OutputStream render(Form form){
		OutputStream out = new ByteArrayOutputStream();
		OutputStreamWriter writer = new OutputStreamWriter(out);
		Configuration cfg = new Configuration();
		Resource resource = new FileSystemResource("c:\\helmlabs\\source\\grouper-management-suite\\grouper-forms\\src\\main\\resources\\themes\\default\\");
		try {
			Template template = null;
			cfg.setDirectoryForTemplateLoading(resource.getFile());
			template = cfg.getTemplate("form-head.ftl");
			Map formConfig = new HashMap();
			formConfig.putAll(new BeanMap(form));
			template = cfg.getTemplate("form-head.ftl");
			template.process(formConfig, writer);
			for (AbstractField field : form.getFields()){
				Map config = new HashMap();
				config.putAll(new BeanMap(field));
				template = cfg.getTemplate(field.getClass().getSimpleName().toLowerCase() + ".ftl");
				template.process(config, writer);
			}
			template = cfg.getTemplate("form-foot.ftl");
			template.process(formConfig, writer);
			
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		
		return out;
		
	}

}
